home *** CD-ROM | disk | FTP | other *** search
- Path: freya.cs.umass.edu!ramanath
- From: ramanath@freya.cs.umass.edu (Kumaresan Ramanathan)
- Newsgroups: comp.lang.c
- Subject: Macros in C (Disadvantages?)
- Date: 5 Jan 1996 17:08:33 GMT
- Organization: CS Dept., Umass-Amherst
- Message-ID: <4cjluh$gva@kernighan.cs.umass.edu>
- NNTP-Posting-Host: freya.cs.umass.edu
- X-Newsreader: TIN [version 1.2 PL2]
-
- Folks,
- I have heard many people claim that macros are inherently dangerous and
- should never be used.
- However, I have always found them useful for extending the language to
- do what C normally cannot do.
-
- I have been thinking about writing a general purpose code generator as
- freeware to provide a powerful mechanism for creating user defined
- extensions to C. I would not like to create something that is even worse
- than the current cpp!
-
- I am aware of the following disadvantages to macros in C (and C++).
-
- 1) Macros are text substitution. So
- #define square(x) x*x is bad if I use square(x++)
- 2) Macros have no scope. That is {} do not nest the definition of macros
-
- 3) Most current debuggers do not allow us to step through a block of code
- inside a macro. For example,
- #define myfor(x,y,z) for(i=x;i<=y;i++){z}
-
- for(1,10,
- printf("The valuse of i is");
- printf(" %d \n",i);
- )
-
- Most cpp's will reduce this to a single line. So most debuggers (on UNIX)
- will not have line number info to step through the two different printf's.
-
- Notice that I am only talking about the use of cpp to extend the C language,
- not about using constants as in:
- #define SOMETHING 123
-
- 4) Macros (unlike dedicated code generators) cannot create new symbols
- on the fly (even with contrived 'pastes', it is difficult...)
- For example in the above for() example , it would have been nice to if we
- could have created a new index variable for each level of nested for() so
- that there were no name clashes.
-
- 5) Macros can only generate code inplace. So I cannot have a macros that
- is invoked using :
-
- main()
- {
- button(OK, printf("OK was pressed");)
- button(CANCEL,printf("Cancel was pressed");)
- }
-
- that *create* new functions like:
- void gensym1()
- {printf("OK was pressed"); }
-
- and
- void gensym2()
- {printf(Cancel was pressed");}
-
- General purpose code generators should have no trouble with this.
-
- --------------------------------------------------------------------------
- So my query is specifically:
- What can code generators (written from scratch) do that macros cannot.
- Have I missed any disadvantages of macros (for the purpose of extending
- the C language) ?
- Is it really necessary to extend the C language (like the way lisp users
- are accustomed to... ?
-
- I will post a digest of responses sent to ramanath@cs.umass.edu
-
-
- Thanks.
- --- Kumaresan
-